# -*- coding: utf-8 -*-
# @Date   : 2020/01/17
# @File   : EC05_ExtGuarAmtToTaxMonthlyIncomePro_GZ.py
# @Author : yanhaopeng

'''eof
name:对外担保金额(总)比月均申报收入总额
code:EC05_ExtGuarAmtToTaxMonthlyIncomePro_GZ_2D
tableName:
columnName:
groups:企业征信模块
dependencies:EC_DSJ_2D,IC_DSJ_2D,TX_GZ_DSJ
type:常用指标
dataSourceType:
eof'''

import sys
import re
import time,datetime
import pandas as pd
from collections import OrderedDict
from dateutil.relativedelta import relativedelta
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
last_month_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d')[:6] for i in range(1, 30)]

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def getTableTX(table_Name):
    '''
    获取表
    :param x:
    :return:
    '''
    try:
        ic_data = TX_GZ_DSJ['data'].get(table_Name)
        if ic_data in null_type_list:
            return None
        else:
            return ic_data if isinstance(ic_data, list) and len(ic_data) > 0 else [{}]
    except:
        return None

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def ECGuarantee():
    data = EC_DSJ_2D['data']
    ##企业征信的担保交易相关还款责任汇总信息
    # 相关还款责任汇总信息   [1..1]
    EBE=getTable(data,"EBE",1)
    if EBE is None:
        return  None
    elif EBE==[{}] or EBE == "":
        return 0
    else:
        # 相关还款责任汇总   [0..1]
        EB05=getTable(EBE[0],"EB05",0)
        if EB05 is None:
            return None
        elif EB05 == [{}] or EB05 == "":
            return 0
        else:
            factor1 = []
            factor2 = []
            # 借贷交易相关还款责任汇总信息段   [0..1]
            EB05A = getTable(EB05[0], "EB05A", 0)
            # 担保交易相关还款责任汇总信息段   [0..1]
            EB05B = getTable(EB05[0], "EB05B", 0)
            if EB05A is None or EB05A == "":
                factor1 = None
            elif EB05A == [{}]:
                factor1 = 0
            else:
                # 借贷交易相关还款责任汇总信息   [0..4]
                EB05AH = getTable(EB05A[0], "EB05AH", 0)
                if EB05AH is None or EB05AH == "":
                    factor1 = None
                elif EB05AH == [{}]:
                    factor1 = 0
                else:
                    for i in EB05AH:
                        try:
                            #责任类型(EB05AD01)为2(保证人\反担保人)的其他借贷交易账户余额(EB05AJ04)
                            EB05AD01 = i.get("EB05AD01")
                            EB05AJ04 = i.get("EB05AJ04")
                            if EB05AD01 in null_type_list or EB05AJ04 in null_type_list:
                                factor1.append(None)
                            elif EB05AD01 == '2' and isfloat(EB05AJ04):
                                factor1.append(float(EB05AJ04))
                            else:
                                factor1.append(0)
                        except:
                            factor1.append(None)
                            continue
                    factor1 = filter(lambda x: x is not None, factor1)
                    if len(factor1) == 0:
                        factor1 = None
                    else:
                        factor1 = sum(factor1)

            if EB05B is None or EB05B == "":
                factor2 = None
            elif EB05B == [{}]:
                factor2 = 0
            else:
                # 担保交易相关还款责任汇总信息   [0..4]
                EB05BH = getTable(EB05B[0], "EB05BH", 0)
                if EB05BH is None or EB05BH == "":
                    factor2 = None
                elif EB05BH == [{}]:
                    factor2 = 0
                else:
                    for i in EB05BH:
                        try:
                            # 责任类型(EB05BD01)为2(保证人\反担保人)的余额(EB05BJ02)
                            EB05BD01 = i.get("EB05BD01")
                            EB05BJ02 = i.get("EB05BJ02")
                            if EB05BD01 in null_type_list or EB05BJ02 in null_type_list:
                                factor2.append(None)
                            elif EB05BD01 == '2' and isfloat(EB05BJ02):
                                factor2.append(float(EB05BJ02))
                            else:
                                factor2.append(0)
                        except:
                            factor2.append(None)
                            continue
                    factor2 = filter(lambda x: x is not None, factor2)
                    if len(factor2) == 0:
                        factor2 = None
                    else:
                        factor2 = sum(factor2)


    if factor1 is None and factor2 is None:
        return None
    elif factor1 is None and factor2 is not None:
        return factor2
    elif factor1 is not None and factor2 is None:
        return factor1
    else:
        return factor1+factor2

def ICGuarantee():
    data = IC_DSJ_2D['data']
    # 信贷交易信息概要   [1..1]
    PCO = getTable(data, "PCO", 1)
    if PCO is None:
        return None
    elif PCO == [{}] or PCO == "":
        return 0
    else:
        # 信贷交易信息概要信息单元   [0..1]
        PC02 = getTable(PCO[0], "PC02", 0)
        if PC02 is None:
            return None
        elif PC02 == [{}] or PC02 == "":
            return 0
        else:
            # 相关还款责任汇总信息段   [0..1]
            PC02K = getTable(PC02[0], "PC02K", 0)
            if PC02K is None or PC02K == "":
                return None
            elif PC02K == [{}]:
                return 0
            else:
                # 相关还款责任汇总信息   [1..4]
                PC02KH = getTable(PC02K[0], "PC02KH", 1)
                if PC02KH is None or PC02KH == "":
                    return None
                elif PC02KH == [{}]:
                    return 0
                factor=[]
                for i in PC02KH:
                    try:
                        # 还款责任类型(PC02KD02)∈(1(担保责任))的余额(PC02KJ02)加总
                        PC02KD02 = i.get('PC02KD02')
                        PC02KJ02 = i.get('PC02KJ02')
                        if PC02KD02 in null_type_list or PC02KJ02 in null_type_list:
                            factor.append(None)
                        elif PC02KD02 == "1" and isfloat(PC02KJ02):
                            factor.append(float(PC02KJ02))
                        else:
                            factor.append(0)
                    except:
                        factor.append(None)
                        continue

                factorNotNone = filter(lambda x: x is not None, factor)
                if len(factorNotNone) == 0:
                    return None
                else:
                    return sum(factorNotNone)

def getTableEG(table_Name):
    try:
        null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
        data = EG_DSJ['data']['R1103V3'][0].get(table_Name)
        if data in null_type_list:
            return None
        else:
            if isinstance(data, list) and len(data) >= 1:
                return data
            else:
                return [{}]
    except:
        return None

# 纳税人类型
def TaxerType():
    try:
        syptSwdjxx = getTableTX('syptSwdjxx')
        if syptSwdjxx == [{}] or syptSwdjxx is None:
            return None
        else:
            NSRZG_DM = syptSwdjxx[0].get('NSRZG_DM')
            if NSRZG_DM in null_type_list:
                return None
            elif NSRZG_DM not in null_type_list and NSRZG_DM in ['201', '202', '203', '204', '205']:
                return NSRZG_DM
            else:
                return u'其他'
    except:
        return None

# 一般纳税人
def ybnsr():
    try:
        syptZzsybnsr = getTableTX('syptZzsybnsr')
        if syptZzsybnsr is None or syptZzsybnsr == [{}]:
            return None
        else:

            # 可能存在统一年月 存在多次数据需要 用dict去重
            Reven_list = OrderedDict()
            for k in last_month_list:
                Reven_list.update({k: 0})
            flag = []

            revenue = {}
            flag = []
            for i in syptZzsybnsr:
                ND = i.get('ND')
                YF = i.get('YF')
                noneCont = 0
                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                       '08', '09', '10', '11', '12']:
                    # 按适用税率计税销售额(ASYSLJSDNSJCYBJSE)
                    if isfloat(i.get('ASYSLJSDNSJCYBJSE')):
                        a1 = float(i.get('ASYSLJSDNSJCYBJSE'))
                    else:
                        a1 = 0
                        noneCont += 1
                    # “按简易办法计税销售额(AJYZSBFZSHWXSE)”
                    if isfloat(i.get('AJYZSBFZSHWXSE')):
                        a2 = float(i.get('AJYZSBFZSHWXSE'))
                    else:
                        a2 = 0
                        noneCont += 1
                    # 免、抵、退办法出口销售额(MDTBFCKHWXSE)
                    if isfloat(i.get('MDTBFCKHWXSE')):
                        a3 = float(i.get('MDTBFCKHWXSE'))
                    else:
                        a3 = 0
                    # 免税销售额(MSHWJLWXSE)
                    if isfloat(i.get('MSHWJLWXSE')):
                        a4 = float(i.get('MSHWJLWXSE'))
                    else:
                        a4 = 0
                        noneCont += 1
                    if noneCont == 4:
                        flag.append(None)
                    else:
                        # 存入每个月的收入
                        revenue.update({ND + YF: a1 + a2 + a3 + a4})
                        key = str(ND) + str(YF)
                        Reven_list.update({key: a1 + a2 + a3 + a4})
            if revenue == {} or len(flag) == len(syptZzsybnsr):
                return None
            else:
                if  Reven_list.values()[0] != 0:
                    Reven2Y_Ave = round(sum(Reven_list.values()[0:24])/24,4)
                else:
                    Reven2Y_Ave = round(sum(Reven_list.values()[1:25])/24,4)



                return Reven2Y_Ave
    except:
        return None

# 小规模纳税人
def xgm():
    try:
        syptZzsxgm = getTableTX('syptZzsXgm')
        if syptZzsxgm is None or syptZzsxgm == [{}]:
            return None
        else:
            # 可能存在统一年月 存在多次数据需要 用dict去重
            Reven_list = OrderedDict()
            for k in last_month_list:
                Reven_list.update({k: 0})
            revenue = {}

            flag = []
            for i in syptZzsxgm:
                ND = i.get('ND')
                YF = i.get('YF')
                noneCount = 0
                if ND not in null_type_list and YF in ['01', '02', '03', '04', '05', '06', '07',
                                                       '08', '09', '10', '11', '12']:
                    # “应征增值税货物及劳务不含税销售额(YZZZSHWJLWBHSXSEBNBQ)”
                    if isfloat(i.get('YZZZSHWJLWBHSXSEBNBQ')):
                        a1 = float(i.get('YZZZSHWJLWBHSXSEBNBQ'))
                    else:
                        a1 = 0
                        noneCount += 1
                    # “销售、出租不动产不含税销售额(XSCZBDCBHSXSE)”
                    if isfloat(i.get('XSCZBDCBHSXSE')):
                        a2 = float(i.get('XSCZBDCBHSXSE'))
                    else:
                        a2 = 0
                        noneCount += 1
                    # “销售使用过的应税固定资产不含税销售额(XSSYGDYSGDZCBHSXSEBNBQ)”
                    if isfloat(i.get('XSSYGDYSGDZCBHSXSEBNBQ')):
                        a3 = float(i.get('XSSYGDYSGDZCBHSXSEBNBQ'))
                    else:
                        a3 = 0
                        noneCount += 1
                    # “免税货物及劳务销售额(MSHWJLWXSEBNBQ)”
                    if isfloat(i.get('MSHWJLWXSEBNBQ')):
                        a4 = float(i.get('MSHWJLWXSEBNBQ'))
                    else:
                        a4 = 0
                        noneCount += 1
                    # 出口免税货物销售额(CKMSHWXSEBNBQ)
                    if isfloat(i.get('CKMSHWXSEBNBQ')):
                        a5 = float(i.get('CKMSHWXSEBNBQ'))
                    else:
                        a5 = 0
                        noneCount += 1
                    # 字段都有问题
                    if noneCount == 5:
                        flag.append(None)
                    else:
                        revenue.update({ND + YF: a1 + a2 + a3 + a4 + a5})
                        key = str(ND) + str(YF)
                        Reven_list.update({key: a1 + a2 + a3 + a4+ a5})


                else:

                    flag.append(None)

            if revenue == {} or len(flag) == len(syptZzsxgm):
                return None
            else:
                if  Reven_list.values()[0] !=0:
                    Reven2Y_Ave = round(sum(Reven_list.values()[0:24])/24,4)
                    print(1)

                elif Reven_list.values()[0] == 0 and Reven_list.values()[1] != 0:
                    Reven2Y_Ave = round(sum(Reven_list.values()[1:25])/24,4)

                elif Reven_list.values()[0] == 0 and Reven_list.values()[1] ==0 and Reven_list.values()[2] != 0:
                    Reven2Y_Ave = round(sum(Reven_list.values()[2:26])/24,4)

                else:
                    Reven2Y_Ave = round(sum(Reven_list.values()[3:27])/24,4)

                return Reven2Y_Ave
    except:
        return None

# 月均申报收入总和
def MonthlyIncomeReportAmt():
    try:
        taxerType = TaxerType()
        # 一般纳税人
        if taxerType in ['201', '202', '203']:
            result = ybnsr()
            if result is not None:
                return round(result, 4)
            else:
                return None
        # 小规模
        elif taxerType in ['204', '205']:
            result = xgm()
            if result is not None:
                return round(result, 4)
            else:
                return None

        # 其他情况
        elif taxerType is None or taxerType == u'其他':
            syptZzsxgm = getTableTX('syptZzsXgm')
            syptZzsybnsr = getTableTX('syptZzsybnsr')
            # 二者均为空
            if (syptZzsybnsr is None or syptZzsybnsr == [{}]) and (syptZzsxgm is None or syptZzsxgm == [{}]):
                return None
            # 二者均不为空
            elif syptZzsxgm not in [None, [{}]] and syptZzsybnsr not in [None, [{}]]:
                # 取出小规模纳税人表 和 一般纳税人表中 缴税年度和月份进行比较
                ybnsr_list2 = []
                xgm_list2 = []

                for i in syptZzsxgm:
                    ND = i.get('ND')
                    YF = i.get('YF')
                    try:
                        d = ND + YF
                    except:
                        continue
                    if isfloat(d):
                        xgm_list2.append(float(d))
                    else:
                        pass
                if xgm_list2[0] != 'None':
                    xgm_list = round(sum(xgm_list2[0:24]) / 24, 4)

                elif xgm_list2[0] == 'None' and xgm_list2[1] != 'None':
                    xgm_list = round(sum(xgm_list2[1:25]) / 24, 4)

                elif xgm_list2[0] == 'None' and xgm_list2[1] == 'None' and xgm_list2[2] != 'None':
                    xgm_list = round(sum(xgm_list2[2:26]) / 24, 4)

                else:
                    xgm_list = round(sum(xgm_list2[3:27]) / 24, 4)

                for i in syptZzsybnsr:
                    ND = i.get('ND')
                    YF = i.get('YF')
                    try:
                        d = ND + YF
                    except:
                        continue
                    if isfloat(d):
                        ybnsr_list2.append(float(d))
                    else:
                        pass
                if ybnsr_list2[0] != 'None':
                    ybnsr_list = round(sum(ybnsr_list2[0:24]) / 24, 4)

                elif ybnsr_list2[0] == 'None' and ybnsr_list2[1] != 'None':
                    ybnsr_list = round(sum(ybnsr_list2[1:25]) / 24, 4)

                elif ybnsr_list2[0] == 'None' and ybnsr_list2[1] == 'None' and ybnsr_list2[2] != 'None':
                    ybnsr_list = round(sum(ybnsr_list2[2:26]) / 24, 4)

                else:
                    ybnsr_list = round(sum(ybnsr_list2[3:27]) / 24, 4)

                if ybnsr_list == [] and xgm_list == []:
                    return None
                elif ybnsr_list != [] and xgm_list != []:
                    if max(ybnsr_list) >= max(xgm_list):
                        result = ybnsr()
                        if result is not None:
                            return round(result, 4)
                        else:
                            return None
                    else:
                        result = xgm()
                        if result is not None:
                            return round(result, 4)
                        else:
                            return None
                elif ybnsr_list != [] and xgm_list == []:
                    result = ybnsr()
                    if result is not None:
                        return round(result, 4)
                    else:
                        return None
                elif ybnsr_list == [] and xgm_list != []:
                    result = xgm()
                    if result is not None:
                        return round(result, 4)
                    else:
                        return None
                else:
                    assert False
            # 一般纳税人表为空 小规模不为空 用小规模纳税表计算
            elif syptZzsybnsr in [None, [{}]] and syptZzsxgm not in [None, [{}]]:
                result = xgm()
                if result is not None:
                    return round(result, 4)
                else:
                    return None
            # 一般纳税人不为空 小规模为空 用一般纳税人表计算
            elif syptZzsybnsr not in [None, [{}]] and syptZzsxgm in [None, [{}]]:
                result = ybnsr()
                if result is not None:
                    return round(result, 4)
                else:
                    return None
        else:
            assert False
    except:
        return None

def EC05_ExtGuarAmtToTaxMonthlyIncomePro():
    Factor1 = ICGuarantee()
    Factor2 = ECGuarantee()
    Factor3 = MonthlyIncomeReportAmt()
    print(Factor3)
    if Factor1==0 and Factor2==0 and Factor3==0:
        return 0
    elif Factor3 == 0 or Factor3 is None:
        return u'缺失值'
    elif Factor1 is None and Factor2 is None:
        return u'缺失值'
    else:
        if Factor1 is None:
            Factor1 = 0.0
        else:
            Factor1 = Factor1
        if Factor2 is None:
            Factor2 = 0.0
        else:
            Factor2=Factor2

        result = (float(Factor1) + float(Factor2)) / float(Factor3)
        return round(result, 4)

result = EC05_ExtGuarAmtToTaxMonthlyIncomePro()

if __name__ == "__main__":
    import json
    with open("E:\\data(3).json",'r')as f:

        datas = json.load(f,strict=False)
        EC_DSJ_2D = datas.get("EC_DSJ_2D")
        IC_DSJ_2D = datas.get("IC_DSJ_2D")
        TX_GZ_DSJ = datas.get("TX_GZ_DSJ")

        result = EC05_ExtGuarAmtToTaxMonthlyIncomePro()
        print("result =",result)